
package com.hxrk.cecardvr;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hxrk.easyface.EasyFace;
import com.hxrk.jni.Mp4v2Native;

import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.util.List;

import static org.opencv.imgproc.Imgproc.INTER_LINEAR;

public class FaceActivity extends Activity implements View.OnClickListener, CvUSBPreview.CvCameraViewListener, FaceService.OnFaceListener {
    private static final String TAG = "MainActivity";
    private Context mContext;

    private TextView tv_faceNumber;

    private CvUSBPreview cvUSBPreview;

    private ViewfinderView viewfinderView;

    private ServiceConnection connection;
    private FaceService faceService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);
        mContext = this;
        MyApplication.g_Previewstatus = 1;
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.post(new Runnable() {
            @Override
            public void run() {
                viewfinderView.setWH(viewfinderView.getWidth(), viewfinderView.getHeight());
                viewfinderView.setResources(R.drawable.qrcode_scan_line, 0, "");
                viewfinderView.drawViewfinder();
            }
        });

//        tv_faceNumber = (TextView) findViewById(R.id.tv_faceNumber);

        cvUSBPreview = (CvUSBPreview) findViewById(R.id.CvSurfaceViewPlay);
        cvUSBPreview.setCvCameraType(2);
        cvUSBPreview.setCvCameraViewListener(this);
        onBindService();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Toast tst;
        switch (v.getId()) {
        }
    }

    public void onBindService() {
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                faceService = ((FaceService.FaceServiceBinder) service).getService();
                faceService.setOnFaceListener(FaceActivity.this);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                LogUtils.d("FaceService  onServiceDisconnected");
            }
        };

        Intent intent = new Intent(this, FaceService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    // Activity创建或者从后台重新回到前台时被调用
    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.d(TAG, "onStart called.");
    }

    // Activity从后台重新回到前台时被调用
    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtils.d(TAG, "onRestart called.");
    }

    // Activity创建或者从被覆盖、后台重新回到前台时被调用
    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.d(TAG, "onResume called.");

    }

    // Activity窗口获得或失去焦点时被调用,在onResume之后或onPause之后
    /*
     * @Override public void onWindowFocusChanged(boolean hasFocus) {
     * super.onWindowFocusChanged(hasFocus); LogUtils.i(TAG,
     * "onWindowFocusChanged called."); }
     */
    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.d(TAG, "onPause called.");
    }

    // 退出当前Activity或者跳转到新Activity时被调用
    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.d(TAG, "onStop called.");
    }

    // 退出当前Activity时被调用,调用之后Activity就结束了
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestory called.");
    }

    /**
     * Activity被系统杀死时被调用. 例如:屏幕方向改变时,Activity被销毁再重建;当前Activity处于后台,系统资源紧张将其杀死.
     * 另外,当跳转到其他Activity或者按Home键回到主屏时该方法也会被调用,系统是为了保存当前View组件的状态. 在onPause之前被调用.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * Activity被系统杀死后再重建时被调用.
     * 例如:屏幕方向改变时,Activity被销毁再重建;当前Activity处于后台,系统资源紧张将其杀死,用户又启动该Activity.
     * 这两种情况下onRestoreInstanceState都会被调用,在onStart之后.
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        LogUtils.d("width = " + width + "     height = " + height);
    }

    @Override
    public void onCameraViewStopped() {

    }

    private Mat mRgba;
    private Mat mGray;
    Mat[] mats;

    @Override
    public Mat onCameraFrame(CvUSBPreview.CvCameraViewFrame inputFrame) {
        mRgba = inputFrame.rgba();

//        EasyFace.getInstance().nativeDrawFrame(mRgba.dataAddr(), mRgba.rows(), mRgba.cols());

        //尺寸调整
//        Imgproc.resize(mRgba,des, new Size(mRgba.cols()/2,mRgba.rows()/2),0,0,INTER_LINEAR);
//
//        EasyFace.getInstance().nativeProcessFrame(des.dataAddr(), des.rows(), des.cols());
        return mRgba;
    }

    private int SuccessNumber = 0;
    private int FailNumber = 0;
    private int FaceNumber = 0;

    @Override
    public void onMessage(String faceID) {
        MyApplication.g_Previewstatus = 0;
        this.finish();

//        try {
//            if (faceID.equals("0") || faceID.equals("-1")){
//                CamService.FaceStatus = 0;
//                Mp4v2Native.getInstance().faceStart(0, 1);
//                Bundle bundle = new Bundle();
//                bundle.putInt("Result", 0);
//                bundle.putInt("FaceNumber", FaceNumber);
//                bundle.putInt("FailNumber", FailNumber);
//                MyApplication.mDvrManager.mDvrCallBack.doFaceResult(bundle);
//                LogUtils.i("onMessage向主程序反馈识别失败");
//                this.finish();
//            }else {
//                CamService.FaceStatus = 0;
//                Mp4v2Native.getInstance().faceStart(0, 1);
//
//                Bundle bundle = new Bundle();
//                bundle.putString("FaceID", faceID);
//                bundle.putInt("Result", 1);
//                MyApplication.mDvrManager.mDvrCallBack.doFaceResult(bundle);
//                LogUtils.i("onMessage向主程序反馈人脸识别结果");
//                this.finish();
//            }
//
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
    }

    int FaceNumebrTik = 0;

    @Override
    public void onFaceNumber(int faceNumber) {

    }

    @Override
    public void onStopFace() {
        MyApplication.g_Previewstatus = 0;
        this.finish();
    }
}
